package com.bite.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bite.common.core.constants.Constants;
import com.bite.common.core.domain.TableDataInfo;
import com.bite.common.core.enums.ExamListType;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.common.security.exception.ServiceException;
import com.bite.common.security.service.TokenService;
import com.bite.friend.domain.exam.Exam;
import com.bite.friend.domain.exam.dto.ExamQueryDTO;
import com.bite.friend.domain.exam.dto.ExamRankQueryDTO;
import com.bite.friend.domain.exam.vo.ExamVO;
import com.bite.friend.domain.user.User;
import com.bite.friend.domain.user.UserExam;
import com.bite.friend.domain.user.vo.UserRankVO;
import com.bite.friend.manager.ExamCacheManager;
import com.bite.friend.manager.UserCacheManager;
import com.bite.friend.mapper.exam.ExamMapper;
import com.bite.friend.mapper.user.UserExamMapper;
import com.bite.friend.service.user.IUserExamService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
* @author 17450
* @description 针对表【tb_user_exam】的数据库操作Service实现
* @createDate 2025-05-30 11:41:41
*/
@Service
public class UserExamServiceImpl implements IUserExamService {

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserCacheManager userCacheManager;

    @Override
    public int enter(String token, Long examId) {
        Exam exam = examMapper.selectById(examId);
        if (exam == null) {
            throw new ServiceException(ResultCode.EXAM_NOT_EXISTS);
        }
        if (exam.getStartTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
//        Long userId = tokenService.getUserId(token, secret);

        Long userId = ThreadLocalUtil.get(Constants.THREAD_LOCAL_USER_ID, Long.class);
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examId)
                .eq(UserExam::getUserId, userId));
        if (userExam != null) {
            throw new ServiceException(ResultCode.FAILED_USER_ENTER_EXAM);
        }

        // 添加到Redis和MySQL
        examCacheManager.saveUserExamCache(userId, examId);
        userExam = new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        return userExamMapper.insert(userExam);
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        Long userId = ThreadLocalUtil.get(Constants.THREAD_LOCAL_USER_ID, Long.class);
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        // 从Redis中获取
        Long size = examCacheManager.getListSize(examQueryDTO.getType());
        if (size == null || size <= 0) {
            // 从数据库获取并刷新缓存
//            List<ExamVO> list = examMapper.list(examQueryDTO);
            examCacheManager.refreshCache(examQueryDTO.getType());
        }
        size = examCacheManager.getListSize(examQueryDTO.getType());
        List<ExamVO> examVOList = examCacheManager.getExamVOList(examQueryDTO);
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList, size);
    }

    @Override
    public TableDataInfo rankList(ExamRankQueryDTO examRankQueryDTO) {
        Long examId = examRankQueryDTO.getExamId();
        // 从Redis中获取
        Long size = examCacheManager.getRankListSize(examId);
        if (size == null || size <= 0) {
            // 从数据库获取并刷新缓存
            examCacheManager.refreshRankListCache(examId);
            size = examCacheManager.getRankListSize(examId);
        }
        List<UserRankVO> userRankVOList = examCacheManager.getRankVOList(examRankQueryDTO);
        assembleUserRankList(userRankVOList);

        if (CollectionUtil.isEmpty(userRankVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(userRankVOList, size);
    }

    private void assembleUserRankList(List<UserRankVO> userRankVOList) {
        if (CollectionUtil.isEmpty(userRankVOList)) return;

        userRankVOList.forEach(userRankVO -> {
            User user = userCacheManager.getByUserId(userRankVO.getUserId());
            userRankVO.setNickName(user.getNickName());
        });
    }
}




